<template>
	<div v-swiper:mySwiper="swiperOption">
		<div class="swiper-wrapper">
			<div class="swiper-slide" :key="item.id" v-for="(item,index) in imgArray" v-bind:style="{width:bCellSize.width + 'px',height:bCellSize.height + 'px' }">
				<router-link :to="{ path: '/WorkDetail', query: { productId: item.id }}">
					<img :src="item.landScapeThumUrl" width="100%" height="100%" @load="imgloadHandle" @error="imgErrorHandle">
				</router-link>
				<div v-bind:class="['bloader-wrapper' ,'bIndex'+index]">
					<div class="loader-inner pacman">
						<div></div>
						<div></div>
						<div></div>
						<div></div>
						<div></div>
					</div>
				</div>
			</div>

		</div>
		<div class="swiper-pagination"></div>
		<div class=".swiper-button-next"></div>
		<div class=".swiper-button-prev"></div>
		<div class="bloader-wrapper1" v-if="imgArray < 1" >
			<div class="loader-inner pacman">
				<div></div>
				<div></div>
				<div></div>
				<div></div>
				<div></div>
			</div>
		</div>
	</div>
</template>
<script>
	import $ from 'jquery'
	import {
		Swiper,
		SwiperSlide,
		directive
	} from 'vue-awesome-swiper'
	import HttpUtil from '../js/HttpUtil.js'
	import UserInfoManager from "../js/UserInfoManager.js"
	import SLMUtil from '../js/SLMUtil.js'

	// import style (>= Swiper 6.x)
	import 'swiper/swiper-bundle.css'

	//父组件传值过来
	export default {
		name: 'BannerPhone',
		props: ["imgArray"],
		data() {
			let that = this
			return {
				isShowPreNext: false,
				bannerSwiper: null,
				bCellSize: {
					width: 480,
					height: 180
				},
				imgArray2: [],
				loadedsClass:[],
				swiperOption: {
					pagination: {
						el: '.swiper-pagination'
					},
					loop: true,
					autoplay: true,
					// 如果需要前进后退按钮
					navigation: {
						nextEl: '.swiper-button-next',
						prevEl: '.swiper-button-prev',
					},
					on: {
						touchStart: function(swiper, event) {
							that.destoryTimer()
						},
						touchEnd: function(swiper, event) {
							that.startTimer()
						},
						slideChange: function(event) {
							//console.log("滚动到下一个2"+event)
							for(var i = 0; i < that.loadedsClass.length;i++) {
								let className = that.loadedsClass[i]
								var oList = document.getElementsByClassName(className);
								for(var j = 0;j < oList.length;j++) {
									let curLoad = oList[j]
									//console.log("移除："+className)
									curLoad.parentNode.removeChild(curLoad)
								}
							}
							
						}
						
					}
				},
				timer: null,
				timeDict: {
					"firstPicCompleteTime": 0,
					"mountedTime": 0
				},
			}
		},
		components: {
			Swiper,
			SwiperSlide,
		},
		directives: {
			swiper: directive
		},
		mounted() {
			// console.log('imgData:'+this.imgArray)
			var timestamp = new Date().getTime();
			this.timeDict.mountedTime = timestamp
			this.timeOutHandle()

			this.windowWidth = document.documentElement.clientWidth;
			let that = this;
			let size = that.getImgsLayout(0)
			that.bCellSize = size
			console.log("bCellSize高度：" + that.bCellSize.width)

			$(window).resize(function() {
				console.log("jquery imgs监听到窗口变化");
				that.bCellSize = that.getImgsLayout(0)
			});
			that.startTimer()

			this.$once('hook:beforeDestroy', () => {
				that.destoryTimer()
				console.log("停止定时器，banner 控制器销毁");
			})
		},
		methods: {
			imgloadHandle(event) {

				if (this.timeDict.firstPicCompleteTime == 0) {
					var timestamp = new Date().getTime();
					this.timeDict.firstPicCompleteTime = timestamp

					let mountedTime = this.timeDict.mountedTime
					var timeInterval = (timestamp - mountedTime) / 1000
					console.log("第一张banner图片出现耗时：" + timeInterval + "秒")
					this.updateUserRefreshPageTime(timeInterval)
				}
				let img = event.srcElement;
				let curLoader = this.findLoadNodeByCurImg(img)
				if (curLoader) {
					this.closeLoaderAnimation(curLoader)
				} else {
					console.log("警告：有未找到的banner loader")
				}
			},
			imgErrorHandle(event) {
				console.log("图片加载出错")
				let img = event.srcElement;
				img.src = this.defaultImg;
				img.onerror = null; //防止闪图
				let curLoader = this.findLoadNodeByCurImg(img)
				if (curLoader) {
					this.closeLoaderAnimation(curLoader)
				}
			},
			findLoadNodeByCurImg: function(curImg) { //找到加载中的那个div
				let parent = curImg.parentNode.parentNode
				let childNodes = parent.childNodes
				for (var i = 0; i < childNodes.length; i++) {
					let curNode = childNodes[i]
					let curClassName = curNode.className
					console.log("curNode:" + curClassName)
					if (curClassName.indexOf("bloader-wrapper") != -1) {
						console.log("找到加载中元素。。。总个数：" + this.imgArray.length)
						console.log(curNode)
						let classList = curNode.classList
						if(classList.length > 1) {
							let indexClassName = classList.item(1)
							console.log("得到bIndex："+indexClassName)
							if (indexClassName.indexOf("bIndex") != -1) {
								this.addStyleForLoaderBug(indexClassName)
							}
						}
						return curNode
					}
				}
				return null
			},
			closeLoaderAnimation: function(animationNode) {
				//当class为project的元素上没有这个CSS类时，它就新增这个CSS类；如果class为project的元素有了这个CSS类，它就是删除它。就是反转操作。
				animationNode.classList.toggle('bloadedComplete');
			},
			addStyleForLoaderBug: function(loaderClassName) {//解决一个loading不消失的bug
				console.log("添加style开始："+loaderClassName)
				this.loadedsClass.push(loaderClassName)
				//添加
				// var style = document.createElement('style');
				// style.type = 'text/css';
				// style.id = 'add-style-id';
				// style.innerHTML = "."+loaderClassName+'{ display: none; }';
				// document.getElementsByTagName('head').item(0).appendChild(style);
				// console.log("添加style完成："+loaderClassName)
			},
			timeOutHandle: function() {
				let that = this
				setTimeout(function() {
					// 这里就是处理的事件
					if (that.timeDict.firstPicCompleteTime == 0) {
						console.log("页面加载超时-5秒")
						that.updateUserRefreshPageTime(10.11)
					} else {
						console.log("页面加载未超时-5秒")
					}
				}, 10000);
			},
			updateUserRefreshPageTime: function(duration) {
				if (!UserInfoManager.isLogined()) {
					return
				}
				let userAgent = SLMUtil.getUserAgent()
				console.log("获取到userAgent:"+userAgent)
				let sessionkey = UserInfoManager.getInfo().userExt.sessionKey

				var params = new URLSearchParams();
				params.append('duration', duration);
				params.append('name', "首页耗时:"+userAgent+"版本:"+HttpUtil.vueVersion);
				params.append('sessionkey', sessionkey);
				params.append('type', "1");

				console.log("request加载时长参数：" + JSON.stringify(params))
				let that = this
				HttpUtil.post('Statistics/userRequestDuration.do', params)
					.then(response => {
						console.log("提交加载时长完成：" + JSON.stringify(response.data));
					})
					.catch(function(error) {
						console.log(error);
					});
			},
			startTimer: function() {
				if (this.timer == null) {
					this.timer = setInterval(this.timeInterAction, 4000)
				}
			},
			destoryTimer: function() {
				if (this.timer != null) {
					clearInterval(this.timer);
					this.timer = null;
				}
			},
			timeInterAction: function() {
				this.mySwiper.slideNext(300, false)
			},
			getImgsLayout: function(index) { //高度需要变化
				var widht = 0;
				var height = 0;
				let windowWidth = document.documentElement.clientWidth;
				console.log("宽度变化：" + windowWidth);
				if (index == 0) {
					widht = windowWidth;
					let scale = widht / 1242;
					height = 730 * scale;
				} else {
					widht = (windowWidth - 1) * 0.5;
					let scale = widht / 630;
					height = 831 * scale;
				}
				return {
					width: widht,
					height: height
				};
			}
		}
	}
</script>

<style scoped>
	@import "../css/loader_animation.css";

	.swiper-wrapper {
		position: relative;
	}

	.bloader-wrapper1 {
		width: 100%;
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
		padding-top: 15px;
		padding-bottom: 15px;
	}

	.bloader-wrapper {
		position: absolute;
		width: 100%;
		height: 100%;
		top: 0%;
		background-color: rgba(0, 0, 0, 0.3);
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
	}

	.bloadedComplete {
		display: none;
	}
</style>
